<template>
  <div>
    <div class="d-flex justify-center pa-3 ma-1 text-h4 font-weight-bold">
      {{ artInfo.title }}
    </div>
    <div class="d-flex justify-center align-center">
      <div class="d-flex mx-10 justify-center">
        <v-icon class="mr-1" color="indigo" small>{{
          "mdi-calendar-month"
        }}</v-icon>
        <span>{{ artInfo.CreatedAt | dateformat("YYYY-MM-DD HH:MM") }}</span>
      </div>
      <div class="d-flex mr-10 justify-center">
        <v-icon class="mr-1" color="pink" small>{{ "mdi-comment" }}</v-icon>
        <span>{{ total }}</span>
      </div>
      <div class="d-flex mr-10 justify-center">
        <v-icon class="mr-1" color="green" small>{{ "mdi-eye" }}</v-icon>
        <span>{{ artInfo.read_count }}</span>
      </div>
    </div>
    <v-divider class="pa-3 ma-3"></v-divider>
    <v-alert
      class="ma-4"
      elevation="1"
      color="indigo"
      dark
      border="left"
      outlined
      >{{ artInfo.desc }}</v-alert
    >
    <div class="content_box">
      <div
        class="content ma-5 pa-3 text-justify"
        v-html="artInfo.content"
      ></div>
    </div>

    <v-divider class="ma-5"></v-divider>
    <v-sheet class="ma-3 pa-3">
      <div>
        <v-list
          outlined
          class="ma-3 pa-3"
          v-for="item in commentList"
          :key="item.ID"
          v-show="item.status === 1"
        >
          <template>
            <v-list-item>
              <v-list-item-content>
                <v-list-item-title
                  >{{ item.username }}
                  {{
                    item.CreatedAt | dateformat("YYYY-MM-DD HH:MM")
                  }}</v-list-item-title
                >

                <v-list-item-subtitle class="mr-3">{{
                  item.content
                }}</v-list-item-subtitle>
              </v-list-item-content>
            </v-list-item>
          </template>
        </v-list>
      </div>
      <div class="text-center" v-if="commentList">
        <v-pagination
          class="my-2"
          total-visible="7"
          v-model="queryParam.pagenum"
          :length="Math.ceil(total / queryParam.pagesize)"
          @input="getCommentList()"
        ></v-pagination>
      </div>
      <div>
        <template>
          <v-card flat>
            <v-alert
              v-if="success != ''"
              class="ma-3"
              dense
              outlined
              type="error"
              >{{ success }}</v-alert
            >

            <v-alert
              v-if="!headers.username"
              class="ma-3"
              dense
              outlined
              type="error"
              >你还未登录，请<span @click="show_login_form">登录</span
              >后留言</v-alert
            >
            <div v-if="headers.username">
              <v-textarea
                class="mx-3"
                outlined
                v-model="comment.content"
              ></v-textarea>

              <v-btn
                class="ml-3 mb-1"
                dark
                color="indigo"
                small
                @click="pushComment()"
                >确定</v-btn
              >
            </div>
          </v-card>
        </template>
      </div>
    </v-sheet>
  </div>
</template>
<script>
export default {
  head() {
    return {};
  },
  // props: ["id"],
  // async asyncData({ $axios,params }){   let id = params.id   let user = await ($.axios.$get("http://localhost/api/getUserById"+id)).data   return {      user //这里返回的user就是相当于在data方法里返回的，可以通过this.user访问   }}

  async asyncData({ app, params, store }) {
    let art_id = params.id;
    const asyncData = {};

    function htmlDecode(app, text) {
      // return text.replace(/&/g, '&amp').replace(/\"/g, '&quot').replace(/</g, '&lt').replace(/>/g, '&gt');
      text = text.replace(/.\[TOC\]\((.*?)\)/gu, "# $1");

      // $\color{blue}待办$
      // text = text.replace(/\$\\color\{(.*?)\}(.*?)\$/ug, "$2");
      text = text.replace(
        /\$\\color\{(.*?)\}\{?(.*?)\}?\$/gu,
        "<span style='color:$1'>$2</span>"
      );

      text = app.$md.render(text);

      // var matchReg1 = /\<code(.*)\>(.*?)\<\/code\>/gs; 
      var matchReg1 = /<code(.*?)\>(([\s\S])*?)<\/code>/gs; 
      text = text.replace(matchReg1, "<code$1>\n$2</code>");
      text = text.replace(matchReg1, function (rep_new_aa) {
        console.log(rep_new_aa)
        var rep_arr = rep_new_aa.split("\n");
        var rep_new_arr = [];
           rep_new_arr.push("<ul class='pre-numbering'>");
        rep_arr.forEach((item, i) => {
          //排除第一个和最后一个
          if (i != 0 && i < rep_arr.length - 1) {
            item = "<li>" + i + "</li>\n";
          }
          if (i == 0) {
            item = "<li> </li>\n";
          }
          if (i == rep_arr.length - 1) {
            // item = "<li> </li>\n";
          }
          rep_new_arr.push(item);
        });
        rep_new_arr.push("</ul>");

        var rep_new = rep_new_arr.join("");
        rep_new_aa = rep_new_aa + "\n" + rep_new;
        return rep_new_aa;
      });


      text = text.replace(/&lt;/g, "<");
      text = text.replace(/&gt;/g, ">");
      text = text.replace(/&nbsp;/g, " ");
      text = text.replace(/&#39;/g, "'");
      text = text.replace(/&quot;/g, '"');
      return text;
    }

    //getArtInfo
    const { data: res } = await app.$axios.get(`article/info/${art_id}`);

    asyncData.profileInfo = {};
    asyncData.profileInfo.id = 1;
    //导航栏
    const { data: res_cate } = await app.$axios.get("category");
    let cateList = res_cate.data;
    store.commit("add_cateList", cateList);

    //获取个人配置信息
    const { data: res_profileInfo } = await app.$axios.get(
      `profile/${asyncData.profileInfo.id}`
    );
    // this.$root.$emit('msg', res.data.icp_record)
    store.commit("save", res_profileInfo.data.icp_record);
    store.commit("save_profileInfo", res_profileInfo.data);

    // <meta name="keywords" content="js数组添加数据">
    // <meta name="description" content="js中对于数组的操作很常见，下面记录一下js向数组添加元素的方法。    let myArray=[11,22,33];    console.log(原数组：,myArray);    myArray.push(44,55);    console.log(用push在数组后面插入元素：,myArray);    myArray.unshift(66,77);    co..._js数组添加数据">
    // <meta name="csdn-baidu-search" content="{&quot;autorun&quot;:true,&quot;install&quot;:true,&quot;keyword&quot;:&quot;js数组添加数据&quot;}">

    function in_array(search, array) {
      for (var i in array) {
        if (array[i] == search) {
          return true;
        }
      }
      return false;
    }

    function contains(meta, obj) {
      var i = meta.length;
      let del_ids = [];
      while (i--) {
        if (in_array(meta[i].name, obj)) {
          del_ids.push(i);
        }
      }
      return del_ids;
    }

    let del_metads = contains(app.head.meta, [
      "lsblog-baidu-search",
      "keywords",
      "description",
    ]);

    del_metads.forEach((element) => {
      app.head.meta.splice(element, 1);
    });

    var reg = /\[\/\/\]\:\#\(keywords\:(.*?)\)/g;
    //获取文章的keywords
    var keys = reg.exec(res.data.content);
    var keywords = "";
    if (keys != "" && keys != null && keys.length > 0) {
      keywords = keys[1].trim();
    }
    //获取描述
    var descriptions = res.data.content.match(/.\[TOC\]\((.*?)\)/);
    var description = "";

    if (description != "" && description != null && description.length > 0) {
      description = descriptions[1].trim();
    } else {
      description = res.data.desc ? res.data.desc : "";
    }
    app.head.meta.push(
      // {
      //   name: "lsblog-baidu-search",
      //   content:
      //     '{"autorun":true,"install":true,"keyword":"giteaForBT宝塔插件"}',
      // },
      {
        // hid: "keywords",
        name: "keywords",
        content: keywords || "",
      },
      {
        // hid: "description",
        name: "description",
        content: description || "",
      }
    );

    //head
    app.head.title = res.data.title;
    if (res.data.art_type == 0) {
      res.data.content = htmlDecode(app, res.data.content);
    }

    // await new Promise((resolve, reject) => {
    //   setTimeout(() => {
    //     resolve();
    //   }, 2000)
    // });

    asyncData.artInfo = res.data;
    asyncData.art_id = art_id;
    asyncData.id = art_id;

    return asyncData;
  },

  //   async asyncData() {
  //       //  params.id 就是我们传进来的值}
  //     //  let art_id=app.route.params.id;

  //   //getArtInfo
  //       // const { data: res } = await app.$http.get(`article/info/${art_id}`);
  //       // artInfo = res.data;
  // username = 'John Smith';

  //   // const { data: res } = await this.$http.get(`commentfront/${this.id}`, {
  //   //       params: {
  //   //         pagesize: this.queryParam.pagesize,
  //   //         pagenum: this.queryParam.pagenum,
  //   //       },
  //   //     });
  //   //     this.commentList = res.data;
  //   //     this.total = res.total;

  // return {
  //       // artInfo,
  //       username
  //     };
  //     },
  data() {
    return {
      username: "",
      artInfo: {},
      commentList: [],
      comment: {
        content: "",
      },
      total: 0,
      headers: {
        username: "",
        user_id: 0,
      },
      queryParam: {
        pagesize: 5,
        pagenum: 1,
      },
      success: "",
    };
  },
  created() {
    // this.getArtInfo()
    this.getCommentList();
  },
  mounted() {
    this.headers = {
      username: window.sessionStorage.getItem("username"),
      user_id: window.sessionStorage.getItem("user_id"),
    };
  },
  methods: {
    show_login_form() {
      this.$store.commit("save_login_dialog", 1);
      // console.log(this.$store.state.login_dialog);
    },
    // 查询文章
    async getArtInfo() {
      const { data: res } = await this.$http.get(`article/info/${this.id}`);
      this.artInfo = res.data;
    },
    // 获取评论
    async getCommentList() {
      const { data: res } = await this.$http.get(`commentfront/${this.id}`, {
        params: {
          pagesize: this.queryParam.pagesize,
          pagenum: this.queryParam.pagenum,
        },
      });

      this.commentList = res.data;
      this.total = res.total;
    },
    // 发送评论
    async pushComment() {
      const { data: res } = await this.$http.post("addcomment", {
        article_id: parseInt(this.id),
        content: this.comment.content,
        user_id: parseInt(this.headers.user_id),
        username: this.headers.username,
      });
      if (res.status !== 200) return this.$message.error(res.message);
      // this.$message.success("评论成功，待审核后显示");
      this.success = "评论成功，待审核后显示";
      this.comment.content = "";
      setTimeout(() => {
        this.$router.go(0);
      }, 1000);
    },
  },
};
</script>
<style scoped>
.content_box {
  max-width: 100%;
  overflow: hidden;
}
.span {
  width: 100%;
}
.content >>> div,
img,
span {
  width: auto;
  max-width: 100%;
}
</style>

<style>
* {
  padding: 0;
  margin: 0;
}
.container {
}
.container > div.article {
  margin: 1vh 10vh;
  padding: 30px;
  border: 1px solid #ccc;
  /* min-height: 100vh; */
  justify-content: center;
  align-items: center;
  border-radius: 10px;
  display: block;
}
.container > div.footer {
  text-align: center;
  margin: 50px auto;
}

h2 {
  font-size: 20px;
  line-height: 50px;
}
img {
  max-width: 100%;
  display: block;
}
table {
  width: 100%;
  border-spacing: 0;
  border-collapse: collapse;
}
table tr {
  border: 0;
  border-top: 1px solid #ddd;
  background-color: #fff;
}
table tr th {
  font-weight: 700;
  background-color: #eff3f5;
}
table tr td,
table tr th {
  font-size: 14px;
  color: #4f4f4f;
  line-height: 22px;
  border: 1px solid #ddd;
  padding: 8px;
  word-break: normal !important;
  vertical-align: middle;
  border-collapse: collapse;
}

pre {
  padding-left: 50px;
  background: #303030;
  color: #f1f1f1;
  -moz-box-shadow: inset 0 0 10px #000;
  box-shadow: inset 0 0 10px #000;
  position: relative;

}
.v-application pre code {
  /* line-height: 1rem; */
  font-size: 1rem;
line-height: 1.6rem;
overflow-x: auto;
overflow-y: hidden;
display: block;
padding-left: 10px;;
}
.theme--light.v-application code{
  background-color: #444444;

}

pre .pre-numbering {
  position: absolute;
  /* padding: 0.2em 0.4em; */
  width: 48px;
  background-color: #303030;
  top: 0;
  left: 0;
  margin: 0;
  display: inline-block;
  list-style: none;
  text-align: right;
  font-size: 1rem;
line-height: 1.6rem;
  font-family: monospace, monospace;

}
pre .pre-numbering li {
  height: 1rem;
  line-height: 1rem;
  padding: 0;
  margin: 0;
  display:inline-block; 
      border-right: 1px solid #c5c5c5;
      padding-right: 5px;
}

.v-list-item__subtitle {
  white-space: pre-wrap;
}
</style>